const path = require("path")
const isEnvProduction = process.env.NODE_ENV === "production"
const debuggerMode = !(process.env.VUE_APP_NEEDSOURCEMAP === "false")
const onlineDevelopmentMode = process.env.VUE_APP_ONLINE_DEVELOPMENT_MODE === "true"
const CopyWebpackPlugin = require("copy-webpack-plugin")
module.exports = {
  terser: {
    terserOptions: {
      compress: {
        drop_debugger: isEnvProduction && !debuggerMode,
        pure_funcs: (isEnvProduction && !debuggerMode) ? ["console.log", "console.error", "console.warning"] : []
      },
      output: {
        ascii_only: isEnvProduction && !debuggerMode
      }
    }
  },
  configureWebpack: config => {
    if (isEnvProduction) {
      return {
        devtool: debuggerMode ? "eval-source-map" : "source-map"
      }
    } else {
      // 为开发环境修改配置...
      return {
        plugins: [
          new CopyWebpackPlugin({
              patterns: [
                {
                  from: path.resolve("./pluginTemp/source")
                }
              ]
            }
          )
        ]
      }
    }
  },
  publicPath: "auto",
  devServer: {
    open: true,
    proxy: {
      "/api": {
        target: "http://10.15.111.6:8088/",
        changeOrigin: true,
        pathRewrite: {
          "/api": ""
        }
      }
    }
  },
  chainWebpack: (config) => {
    //拼接output.prod.js
    process.env.VUE_APP_PRODCONF && console.log("const Config = ")
    config.when(onlineDevelopmentMode, (config) => {
      config.plugins.delete("hmr")
    })
    config.optimization.splitChunks(false)
    config.plugins.delete("extract-css");
    ["postcss", "scss", "css", "sass", "less", "stylus"].forEach(
      (element) => {
        ["vue-modules", "vue", "normal-modules", "normal"].forEach((m) => {
          config.module
            .rule(element)
            .oneOf(m)
            .uses.delete("extract-css-loader")
            .end()
            .use("vue-style-loader")
            .loader("vue-style-loader")
            .options({
              sourceMap: false,
              shadowMode: false
            })
            .before("css-loader")
        })
      }
    )
    config.resolve.alias
      .set("@", resolve("./src"))
    config.module
      .rule("images")
      .parser({dataUrlCondition: {maxSize: 1000}})
      .set("generator", {filename: "media/[name].[hash:8][ext]"})
    config.module
      .rule("fonts")
      .parser({dataUrlCondition: {maxSize: 1000}})
      .set("generator", {filename: "media/[name].[hash:8][ext]"})
    config.module
      .rule("svg")
      .set("generator", {filename: "media/[name].[hash:8][ext]"})
  }
}

function resolve(dir) {
  return path.join(__dirname, dir)
}